package cc.rboot.degrade.aspect;

import cc.rboot._core.helper.MethodHelper;
import cc.rboot.degrade.annotation.Degrade;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class DegradeAspect {

    @Pointcut("@annotation(cc.rboot.degrade.annotation.Degrade)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Method targetMethod = MethodHelper.get(joinPoint);
        Degrade degrade = targetMethod.getAnnotation(Degrade.class);

        try {
            return joinPoint.proceed();
        } catch (Exception ex1) {
            String executor = degrade.executor();
            Method method = joinPoint.getThis().getClass().getMethod(executor, targetMethod.getParameterTypes());

            if (null != method) {
                try {
                    return method.invoke(joinPoint.getThis(), joinPoint.getArgs());
                } catch (Exception ex2) {
                    throw ex1;
                }
            } else {
                throw ex1;
            }

        }

    }

}
